﻿using Edu.Common;
using Edu.Common.Extensions;
using MainApp.Utils;
using Panuon.WPF.UI;
using System;
using System.IO;
using System.Windows;
using Tools = MainApp.Utils.Tools;

namespace MainApp
{
    /// <summary>
    /// SettingsWindow.xaml 的交互逻辑
    /// </summary>
    public partial class SettingsWindow : WindowX
    {
        public bool IsEditPassswordMode { get; set; }
        public bool IsLoginCompleted { get; set; }

        public SettingsWindow()
        {
            InitializeComponent();

            cboxAutoRun.IsChecked = AppConfig.Current.AutoRun;
            cboxCoverDesktop.IsChecked = AppConfig.Current.CoverDesktop;
            cboxForegroundSlideViewWindow.IsChecked = AppConfig.Current.ForegroundSlideViewWindow;
            txtStartFile.Text = AppConfig.Current.RunFilePath;
            numMaxFreeTimes.Value = AppConfig.Current.MaxFreeTimes;

            cboxAutoRun.Checked += CboxAutoRun_Checked;
            cboxAutoRun.Unchecked += CboxAutoRun_Checked;
            cboxCoverDesktop.Checked += CboxCoverDesktop_Checked;
            cboxCoverDesktop.Unchecked += CboxCoverDesktop_Checked;
            cboxForegroundSlideViewWindow.Checked += CboxForegroundSlideViewWindow_Checked;
            cboxForegroundSlideViewWindow.Unchecked += CboxForegroundSlideViewWindow_Checked;

            numMaxFreeTimes.ValueChanged += NumMaxFreeTimes_ValueChanged;

            Loaded += SettingsWindow_Loaded;
        }

        private void NumMaxFreeTimes_ValueChanged(object sender, Panuon.WPF.SelectedValueChangedRoutedEventArgs<double?> e)
        {
            AppConfig.Current.MaxFreeTimes = e.NewValue ?? 0;
        }

        private void SettingsWindow_Loaded(object sender, RoutedEventArgs e)
        {
            passwordBox.Focus();
        }

        private void CboxAutoRun_Checked(object sender, RoutedEventArgs e)
        {
            AppConfig.Current.AutoRun = cboxAutoRun.IsChecked ?? false;
            Tools.SetAutoRun(cboxAutoRun.IsChecked);
        }

        private void CboxCoverDesktop_Checked(object sender, RoutedEventArgs e)
        {
            var coverDesktop = cboxCoverDesktop.IsChecked ?? false;
            AppConfig.Current.CoverDesktop = coverDesktop;
            if (Application.Current.MainWindow is MainWindow mainWindow)
            {
                mainWindow.OnConverDesktopChanged(coverDesktop);
            }
        }

        private void CboxForegroundSlideViewWindow_Checked(object sender, RoutedEventArgs e)
        {
            AppConfig.Current.ForegroundSlideViewWindow = cboxForegroundSlideViewWindow.IsChecked ?? false;
        }

        private void btnRegister_Click(object sender, RoutedEventArgs e)
        {
            var batFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"addins\\register.bat");
            if (!File.Exists(batFile))
            {
                this.ShowError($"{batFile}文件不存在！");
                return;
            }
            Tools.RunFile(batFile, runasAdmin: true);
        }

        private void btnUnRegister_Click(object sender, RoutedEventArgs e)
        {
            var batFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"addins\\unregister.bat");
            if (!File.Exists(batFile))
            {
                this.ShowError($"{batFile}文件不存在！");
                return;
            }
            Tools.RunFile(batFile, runasAdmin: true);
        }

        private void btnSelectFile_Click(object sender, RoutedEventArgs e)
        {
            var file = Tools.SelectPntFile();
            AppConfig.Current.RunFilePath = file;
            txtStartFile.Text = file;
        }

        private void btnRunFile_Click(object sender, RoutedEventArgs e)
        {
            var file = txtStartFile.Text.Trim();
            if (!file.FileExists()) return;
            PPTTools.RunPPTFile(file);
        }

        private void btnEndSlideView_Click(object sender, RoutedEventArgs e)
        {
            //结束ppt放映
            PPTTools.EndSlideView();
        }

        private void btnClosePntApplication_Click(object sender, RoutedEventArgs e)
        {
            PPTTools.ClosePptApplication();
        }

        private void btnTurnoffMachine_Click(object sender, RoutedEventArgs e)
        {
            var result = this.ShowOkCancelAsk("确定要关闭计算机吗？");
            if (result != MessageBoxResult.OK) return;
            //关闭计算机
            Tools.Shutdown();
        }

        private void btnCloseMe_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            if (!IsEditPassswordMode)
            {
                Close();
                return;
            }
            IsEditPassswordMode = false;
            RefreshLoginUIState();
        }

        private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            if (!IsEditPassswordMode)
            {
                var password = txtPassword.Text?.ToLower();
                if (password.IsNullOrWhiteSpace())
                {
                    this.ShowError("必须输入管理密码！");
                    return;
                }
                var md5 = CryptoHelper.GetMd532StrUpper(password);
                if (md5 != AppConfig.Current.SecrityKey)
                {
                    this.ShowError("输入密码不正确！");
                    return;
                }
                IsLoginCompleted = true;
            }
            else
            {
                var password = newPasswordBox.Text?.ToLower();
                if (password.IsNullOrWhiteSpace())
                {
                    this.ShowError("必须输入新的管理密码！");
                    return;
                }
                var md5 = CryptoHelper.GetMd532StrUpper(password);
                AppConfig.Current.SecrityKey = md5;
                this.ShowError("修改密码成功！");
                IsEditPassswordMode = false;
            }
            RefreshLoginUIState();
        }

        private void btnNumber_Click(object sender, RoutedEventArgs e)
        {
            if (!(sender is System.Windows.Controls.Button button)) return;
            if (!IsEditPassswordMode)
            {
                txtPassword.Text = $"{txtPassword.Text}{button.Content}";
                return;
            }
            newPasswordBox.Text = $"{newPasswordBox.Text}{button.Content}";
        }

        private void btnRemove_Click(object sender, RoutedEventArgs e)
        {
            var str = txtPassword.Text;
            if (str.IsNullOrWhiteSpace() || str.Length == 0) return;
            if (str.Length == 1)
            {
                txtPassword.Text = string.Empty;
                return;
            }
            txtPassword.Text = str.Substring(0, str.Length - 1);
        }

        private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            txtPassword.Clear();
        }

        private void btnEditPassword_Click(object sender, RoutedEventArgs e)
        {
            newPasswordBox.Text = string.Empty;
            IsEditPassswordMode = true;
            RefreshLoginUIState();
        }

        private void RefreshLoginUIState()
        {
            passwordContainer.Visibility = !IsLoginCompleted || IsEditPassswordMode? Visibility.Visible : Visibility.Collapsed;
            loginPasswordContainer.Visibility = IsEditPassswordMode ? Visibility.Collapsed : Visibility.Visible;
            editPasswordContainer.Visibility = IsEditPassswordMode ? Visibility.Visible : Visibility.Collapsed;
        }
    }
}
